import { defineStore } from 'pinia'
import { getDeviceRoleListByCurrentUserAPI } from '@/api/device'

export const useDeviceRoleStore = defineStore('deviceRole', {
  state: () => ({
    deviceRole: new Map<string, {
      // 权限类型 0-仅查看、1-允许控制、3-可管理、4-设备创建者
      roleType?: string,
      // 过期时间
      expiredTime?: string
    }>()
  }),
  actions: {
    updateDeviceRole () {
      return new Promise((resolve) => {
        getDeviceRoleListByCurrentUserAPI().then((res) => {
          res.result().then((rdata) => {
            const deviceRole = new Map()
            const data = rdata.data || []
            for (let i = 0, len = data.length; i < len; i++) {
              const item = data[i]
              deviceRole.set(item.deviceId, {
                roleType: item.roleType,
                expiredTime: item.expiredTime
              })
            }
            this.deviceRole = deviceRole
          }).finally(() => resolve(undefined))
        }).catch(() => resolve(undefined))
      })
    }
  }
})
